<template>
  <div class="position-page page-view">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <div class="list">
        <div class="home-icon">
          <i class="iconfont icon-home"></i>
        </div>
        <div class="item">
          <router-link to="/"><span class="text">首页</span></router-link>
        </div>
        <div class="seperate">
          <i class="iconfont icon-arrow-right-thin"></i>
        </div>
        <div class="item">
          <span class="text">职位管理</span>
        </div>
      </div>
      <h1 class="page-title">职位管理</h1>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar">
      <button @click="handleAddPosition" class="v-button primary" :disabled="!canCreatePosition">
        <i class="iconfont icon-add"></i> 添加职位
      </button>

      <!-- 搜索框 -->
      <div class="search-wrapper">
        <div class="search-input">
          <i class="iconfont icon-search"></i>
          <input
            v-model="searchQuery"
            placeholder="搜索职位名称"
            @keyup.enter="handleSearch"
          />
          <i
            v-if="searchQuery"
            class="iconfont icon-close"
            @click="handleSearchClear"
          ></i>
        </div>
      </div>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-bar">
      <div class="filter-group">
        <label>职位状态:</label>
        <BaseSelect
          v-model="statusFilter"
          :options="statusOptions"
          placeholder="请选择状态"
          @change="handleFilter"
        />
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="data-table">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>职位名称</th>
            <th>状态</th>
            <th>创建时间</th>
            <th>更新时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <template v-for="position in paginatedPositions" :key="position.id">
            <tr>
              <td>{{ position.id }}</td>
              <td class="tree-node">
            <span class="indent" :style="{ paddingLeft: position.level * 20 + 'px' }"></span>
            <i v-if="position.level === 0" class="tree-placeholder"></i>
            <span v-else class="child-prefix">——</span>
            {{ position.name }}
              </td>
              <td>
                <span class="status-badge" :class="position.status == 1 ? 'active' : 'inactive'">
                  {{ position.status == 1 ? '启用' : '禁用' }}
                </span>
              </td>
              <td>{{ formatDate(position.created_at * 1000) }}</td>
              <td>{{ formatDate(position.updated_at * 1000) }}</td>
              <td class="control">
                  <button class="v-button" @click="handleEditPosition(position)" :disabled="!canEditPosition" :title="!canEditPosition ? '您没有权限编辑此职位' : ''">
                    <i class="iconfont icon-edit"></i> 编辑
                  </button>
                  <button class="v-button danger" @click="confirmDelete(position)" :disabled="!canDeletePosition" :title="!canDeletePosition ? '您没有权限删除此职位' : ''">
                    <i class="iconfont icon-delete"></i> 删除
                  </button>
                  <button class="v-button" @click="confirmToggleStatus(position)" :disabled="!canEditPosition" :title="!canEditPosition ? '您没有权限修改此职位状态' : ''">
                    <i class="iconfont icon-switch"></i> {{ position.status == 1 ? '禁用' : '启用' }}
                  </button>
                </td>
            </tr>
          </template>
          <tr v-if="loading">
            <td colspan="6" class="loading">加载中...</td>
          </tr>
          <tr v-else-if="filteredPositions.length === 0">
            <td colspan="6" class="empty-row">
              <i class="iconfont icon-empty"></i>
              <p>暂无数据</p>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper" v-if="totalPages > 0 && !loading">
      <div class="page-info">
        共 {{ filteredPositions.length }} 条记录，第 {{ currentPage }} / {{ totalPages }} 页
      </div>
      <div class="v-pagination">
        <button
          class="v-btn"
          :disabled="currentPage === 1"
          @click="handlePageChange(1)"
        >
          首页
        </button>
        <button
          class="v-btn"
          :disabled="currentPage === 1"
          @click="handlePageChange(currentPage - 1)"
        >
          上一页
        </button>
        <button
          v-for="page in visiblePages"
          :key="page"
          class="v-btn"
          :class="{ active: currentPage === page }"
          @click="handlePageChange(page)"
        >
          {{ page }}
        </button>
        <button
          class="v-btn"
          :disabled="currentPage === totalPages"
          @click="handlePageChange(currentPage + 1)"
        >
          下一页
        </button>
        <button
          class="v-btn"
          :disabled="currentPage === totalPages"
          @click="handlePageChange(totalPages)"
        >
          末页
        </button>
      </div>
    </div>

    <!-- 编辑弹窗 -->
    <vPopup
      v-model="showModal"
      :title="isEdit ? '编辑职位' : '添加职位'"
      confirm-text="确定"
      width="600px"
      :async-confirm="true"
      @confirm="handleSubmit"
    >
      <div class="v-form">
        <div class="form-group">
          <label class="form-label">职位名称</label>
          <input
            v-model="formData.name"
            class="form-input"
            placeholder="请输入职位名称"
          />
        </div>
        
        <div class="form-group">
          <label class="form-label">状态</label>
          <div class="toggle-wrapper">
            <vToggle v-model="formData.status" />
            <span class="toggle-label">{{ formData.status ? '启用' : '禁用' }}</span>
          </div>
        </div>
        
        <div class="form-group">
          <label class="form-label">上级职位（选填）</label>
          <select 
            v-model="formData.parent_id"
            class="form-input"
            :disabled="!rootPositions.length"
          >
            <option value="">无（一级职位）</option>
            <option 
              v-for="pos in rootPositions" 
              :key="pos.id" 
              :value="pos.id"
              :disabled="pos.id === formData.id"
            >
              {{ pos.name }}
            </option>
          </select>
          <div v-if="rootPositions.length === 0" class="form-tip">
            暂无可选的一级职位
          </div>
        </div>
      </div>
    </vPopup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { get, post } from "@/utils/request";
import { formatDate } from "@/utils/date";
import { vConfirm } from "@/plugins/vConfirm";
import { vToast } from "@/plugins/vToast";
import BaseSelect from '@/components/BaseSelect.vue';
import { getPermission } from '@/utils/auth';

// 数据
const positionList = ref([]);
const positionTree = ref([]);
const loading = ref(false);
const searchQuery = ref("");
const statusFilter = ref("");
const currentPage = ref(1);
const pageSize = ref(20);
const expandedNodes = ref([1, 2, 3]); // 默认展开部分节点，可根据实际情况调整

// 直接使用后端返回的职位列表
const filteredPositions = ref([]);

// 分页计算
const totalPages = computed(() => {
  return Math.ceil(filteredPositions.length / pageSize.value);
});

const paginatedPositions = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredPositions.value.slice(start, end);
});

// 可见页码
const visiblePages = computed(() => {
  const pages = [];
  const total = totalPages.value;
  const current = currentPage.value;
  
  // 简化的页码逻辑，只显示5个页码
  let start = Math.max(1, current - 2);
  let end = Math.min(total, start + 4);
  
  if (end - start < 4) {
    start = Math.max(1, end - 4);
  }
  
  for (let i = start; i <= end; i++) {
    pages.push(i);
  }
  
  return pages;
});

// 构建职位树形结构
const buildPositionTree = (positions) => {
  // 创建id到职位的映射
  const positionMap = {};
  positions.forEach(position => {
    positionMap[position.id] = { ...position, children: [], level: 0 };
  });
  
  const rootPositions = [];
  
  // 构建树形结构
  positions.forEach(position => {
    const currentPos = positionMap[position.id];
    
    if (position.parent_id && position.parent_id !== '') {
      // 有父职位
      const parent = positionMap[position.parent_id];
      
      if (parent) {
        parent.children.push(currentPos);
        currentPos.level = parent.level + 1;
      } else {
        // 如果父职位不存在，作为根节点
        rootPositions.push(currentPos);
      }
    } else {
      // 没有父职位的作为根节点
      rootPositions.push(currentPos);
    }
  });
  
  // 按名称排序
  rootPositions.sort((a, b) => a.name.localeCompare(b.name));
  
  // 递归排序子节点
  const sortChildren = (nodes) => {
    nodes.forEach(node => {
      if (node.children && node.children.length > 0) {
        node.children.sort((a, b) => a.name.localeCompare(b.name));
        sortChildren(node.children);
      }
    });
  };
  
  sortChildren(rootPositions);
  
  return rootPositions;
};



// 弹窗相关
const showModal = ref(false);
const isEdit = ref(false);
const editLoading = ref(false);
const formData = ref({
  id: '',
  name: '',
  status: 1,
  parent_id: ''
});

// 一级职位列表（用于选择上级职位）
const rootPositions = computed(() => {
  if (positionTree.value && positionTree.value.length > 0) {
    return positionTree.value.filter(pos => pos.level === 0);
  }
  return [];
});

// 当前用户权限
const currentUserPermission = computed(() => getPermission());

// 权限判断
const canCreatePosition = computed(() => {
  return currentUserPermission.value === 'superadmin';
});

const canEditPosition = computed(() => {
  return currentUserPermission.value === 'superadmin';
});

const canDeletePosition = computed(() => {
  return currentUserPermission.value === 'superadmin';
});

// 状态选项
const statusOptions = [
  { value: '', text: '全部' },
  { value: '1', text: '启用' },
  { value: '0', text: '禁用' }
];

// 加载职位列表
const fetchPositions = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    };
    
    if (searchQuery.value) {
      params.keyword = searchQuery.value;
    }
    
    if (statusFilter.value !== '') {
      params.status = statusFilter.value;
    }
    
    const res = await get("/position/list", params);
    positionList.value = res?.data?.list || [];
    
    // 构建树形结构
    positionTree.value = buildPositionTree(positionList.value);
    
    // 扁平化树形结构用于分页
    const flattenTree = (tree) => {
      let result = [];
      tree.forEach(node => {
        result.push(node);
        if (node.children && node.children.length > 0) {
          result = result.concat(flattenTree(node.children));
        }
      });
      return result;
    };
    
    filteredPositions.value = flattenTree(positionTree.value);
  } catch (error) {
    vToast.error("获取职位列表失败");
    console.error(error);
    positionList.value = [];
    positionTree.value = [];
    filteredPositions.value = [];
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchPositions();
};

// 清空搜索
const handleSearchClear = () => {
  searchQuery.value = "";
  currentPage.value = 1;
  fetchPositions();
};

// 筛选
const handleFilter = () => {
  currentPage.value = 1;
  fetchPositions();
};

// 分页
const handlePageChange = (page) => {
  if (page < 1 || page > totalPages.value) return;
  currentPage.value = page;
};

// 添加职位
const handleAddPosition = () => {
  isEdit.value = false;
  formData.value = {
    id: '',
    name: '',
    status: 1,
    parent_id: ''
  };
  showModal.value = true;
};

// 编辑职位
const handleEditPosition = (position) => {
  isEdit.value = true;
  
  // 查找当前职位的上级职位ID
  let parentId = '';
  if (position.level > 0) {
    // 通过树形结构查找父级
    const findParent = (tree, childId) => {
      for (const node of tree) {
        if (node.children && node.children.some(child => child.id === childId)) {
          return node.id;
        }
        if (node.children && node.children.length > 0) {
          const result = findParent(node.children, childId);
          if (result) {
            return result;
          }
        }
      }
      return '';
    };
    
    parentId = findParent(positionTree.value, position.id);
  }
  
  formData.value = {
    id: position.id,
    name: position.name,
    status: Number(position.status),
    parent_id: parentId
  };
  showModal.value = true;
};

// 提交表单
const handleSubmit = async () => {
  // 验证表单
  if (!formData.value.name.trim()) {
    vToast.error("请输入职位名称");
    return;
  }
  
  editLoading.value = true;
  try {
    if (isEdit.value) {
      // 更新职位
      await post("/position/update", formData.value);
      vToast.success("更新成功");
    } else {
      // 创建职位
      await post("/position/create", formData.value);
      vToast.success("创建成功");
    }
    
    showModal.value = false;
    fetchPositions();
  } catch (error) {
    vToast.error(error?.message || (isEdit.value ? "更新失败" : "创建失败"));
  } finally {
    editLoading.value = false;
  }
};

// 确认删除
const confirmDelete = (position) => {
  vConfirm({
    title: '确认删除',
    content: `确定要删除职位"${position.name}"吗？删除后将无法恢复。`,
    onConfirm: async () => {
      try {
        await post("/position/delete", { id: position.id });
        vToast.success("删除成功");
        fetchPositions();
      } catch (error) {
        vToast.error(error?.message || "删除失败");
      }
    }
  });
};

// 切换状态
const confirmToggleStatus = (position) => {
  const newStatus = position.status == 1 ? 0 : 1;
  vConfirm({
    title: '确认修改状态',
    content: `确定要将职位"${position.name}"${newStatus == 1 ? '启用' : '禁用'}吗？`,
    onConfirm: async () => {
      try {
        await post("/position/update", {
          id: position.id,
          status: newStatus
        });
        vToast.success("状态修改成功");
        fetchPositions();
      } catch (error) {
        vToast.error(error?.message || "状态修改失败");
      }
    }
  });
};

// 监听分页变化
watch(currentPage, fetchPositions);

// 初始化
onMounted(() => {
  fetchPositions();
});
</script>

<style scoped lang="less">
.position-page {
  padding: 20px;
}

/* 操作栏样式 */
.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

/* 筛选栏样式 */
.filter-bar {
  background: var(--v-card-background);
  border-radius: var(--v-card-radius);
  padding: 15px 20px;
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  align-items: center;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-group label {
  font-size: 14px;
  color: var(--v-text-primary);
  white-space: nowrap;
}

/* 搜索框样式 */
.search-wrapper {
  position: relative;
  max-width: 300px;
  width: 100%;
}

.search-input {
  position: relative;
  display: flex;
  align-items: center;
  background: var(--v-input-background);
  border-radius: var(--v-input-radius);
  border: 1px solid var(--v-border-color);
  padding: 8px 12px;
  transition: border-color 0.3s ease;
}

.search-input:focus-within {
  border-color: var(--v-theme);
}

.search-input i {
  color: var(--v-text-light);
  margin-right: 8px;
  font-size: 16px;
}

.search-input input {
  flex: 1;
  border: none;
  background: transparent;
  outline: none;
  color: var(--v-text-primary);
  font-size: 14px;
}

.search-input input::placeholder {
  color: var(--v-text-light);
}

.search-input .icon-close {
  cursor: pointer;
  margin-left: 8px;
  transition: color 0.3s ease;
}

.search-input .icon-close:hover {
  color: var(--v-danger);
}

/* 表格样式 */
.data-table {
  background: var(--v-card-background);
  border-radius: var(--v-card-radius);
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.data-table table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid var(--v-border-color);
}

.data-table th {
  background: rgba(0, 0, 0, 0.02);
  font-weight: 600;
  color: var(--v-text-primary);
  font-size: 14px;
}

.data-table td {
  color: var(--v-text-secondary);
  font-size: 14px;
}

.data-table tr:last-child td {
  border-bottom: none;
}

.data-table tr:hover {
  background: rgba(0, 0, 0, 0.01);
}

/* 状态徽章样式 */
.status-badge {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.active {
  background: rgba(40, 199, 111, 0.1);
  color: var(--v-success);
}

.status-badge.inactive {
  background: rgba(153, 153, 153, 0.1);
  color: var(--v-text-light);
}

/* 操作按钮样式 */
.control {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

/* 使用main.less中定义的统一按钮样式 */
/* 如有特殊需求，请在main.less中统一定义 */

/* 树形结构样式 */
.tree-node {
      display: flex;
      align-items: center;
      position: relative;
    }

    .indent {
      display: inline-block;
    }

    .expand-icon {
      cursor: pointer;
      font-size: 12px;
      width: 16px;
      height: 16px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      margin-right: 4px;
      transition: transform 0.2s;
    }

    .expand-icon.expanded {
      transform: rotate(180deg);
    }

    .custom-icon {
      width: 16px;
      height: 16px;
      border: 1px solid #dcdfe6;
      background-color: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      color: #606266;
      transition: all 0.2s;
    }

    .custom-icon.icon-plus::after {
      content: '+';
      font-weight: bold;
    }

    .custom-icon.icon-minus::after {
      content: '-';
      font-weight: bold;
    }

    .child-indicator {
      width: 8px;
      height: 8px;
      background-color: #67c23a;
      border-radius: 50%;
      margin-right: 10px;
      margin-left: 4px;
    }

    .tree-placeholder {
      width: 16px;
      display: inline-block;
      margin-right: 4px;
    }
    
    .position-page .child-prefix {
      color: #a0a0a0; /* 淡灰色 */
      margin-right: 4px;
    }

/* 加载状态和空状态 */
  .position-page .loading,
  .position-page .empty-row {
    text-align: center;
    padding: 40px;
    color: var(--v-text-light);
  }

  .position-page .empty-row i {
    font-size: 48px;
    margin-bottom: 12px;
    display: block;
  }

  /* 状态标签样式 */
  .position-page .status-badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;

    &.active {
      background-color: rgba(40, 199, 111, 0.1);
      color: var(--v-success);
    }

    &.inactive {
      background-color: rgba(234, 84, 85, 0.1);
      color: var(--v-danger);
    }
  }

  /* 控制按钮区域样式 */
  .position-page .control {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  /* 分页样式 */
  .position-page .pagination-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;

    .page-info {
      color: var(--v-text-light);
      font-size: 14px;
    }

    .v-pagination {
        display: flex;
        gap: 8px;

        .v-btn {
          min-width: 36px;
          height: 36px;
          padding: 0 12px;
          border: 1px solid #dcdfe6;
          background-color: #fff;
          border-radius: 4px;
          cursor: pointer;
          transition: all 0.3s;

          &[disabled] {
            opacity: 0.5;
            cursor: not-allowed;
          }

          &.active {
            background: var(--v-theme);
            color: white;
            border-color: var(--v-theme);
          }
        }
      }
  }

  /* 表单样式 */
  .position-page .v-form {
    padding: 0 10px;
    width: 100%;
  }

  .position-page .v-form .form-group {
    margin-bottom: 0;
  }

  .position-page .v-form .form-input {
    width: 100%;
    box-sizing: border-box;
  }
  
  /* 表单提示样式 */
  .form-tip {
    color: #a0a0a0;
    font-size: 12px;
    margin-top: 4px;
    padding-left: 2px;
  }

  /* 移除页面容器的padding */
  .position-page,
  .page-view {
    padding: 0 !important;
  }
</style>